<template>
  <div class="search-box">
    <div
      class="chart-search lowcode-transition"
      :class="{ 'chart-search-focus': isFocus }"
    >
      <el-popover
        ref="popover"
        trigger="click"
        placement="bottom-start"
        :visible="showPopover"
        popper-class="chart-search-popover"
        width="180px"
      >
        <template #reference>
          <el-input
            v-model.trim="search"
            size="small"
            placeholder="搜索组件"
            :suffix-icon="loading ? 'Loading' : 'Search'"
            @focus="focusHandle(true)"
            @blur="focusHandle(false)"
            @input="searchHandle"
          ></el-input>
        </template>
        <div class="search-list-box">
          <el-scrollbar style="max-height: 500px">
            <el-empty
              v-if="!searchRes.length"
              description="没有找到组件~"
            ></el-empty>
            <div
              class="list-item"
              v-for="item in searchRes"
              :key="item.key"
              @click="selectChartHandle(item)"
            >
              <div class="list-item-img">
                <img :src="fetchImages(item)" class="img" />
              </div>
              <el-tooltip effect="dark" :content="item.title" placement="top">
                <span class="list-item-fs">{{ item.title }}</span>
              </el-tooltip>
            </div>
          </el-scrollbar>
          <div class="popover-modal"></div>
        </div>
      </el-popover>
    </div>
    <chart-change
      :modeList="chartModeList"
      :isFocus="isFocus"
      :mode="chartMode"
      @handleChange="changeChartModeType"
    ></chart-change>
  </div>
</template>

<script setup>
import { ref, onUnmounted, defineProps } from "vue";
import { useStore } from "vuex";
import { isString } from "@/utils/type";
import { addEventListener, removeEventListener } from "@/utils/utils";
import {
  componentInstall,
  fetchConfigComponent,
  fetchChartComponent,
  createComponent,
  fetchImages,
} from "@/packages/index";
import ChartChange from "../ChartChange/index.vue";

const props = defineProps({
  menuOptions: {
    type: Array,
    default: () => [],
  },
});

const store = useStore();

const isFocus = ref(false);
const showPopover = ref(false);
const loading = ref(undefined);
const search = ref(null);
const searchRes = ref([]);
const chartMode = ref(store.getters["chartLayoutStore/chartType"]);

const chartModeList = [
  { label: "单列", icon: "Files", value: "single" },
  { label: "双列", icon: "Menu", value: "double" },
];

// 组件数组提取
const listFormatHandle = (options) => {
  const arr = [];
  for (const item of options) {
    item.list.map((item) => arr.push(...item.list));
  }
  return arr;
};

// 组件列表
const List = listFormatHandle(props.menuOptions);

// 关闭处理
const closeHandle = () => {
  loading.value = undefined;
  showPopover.value = false;
  search.value = null;
  searchRes.value = [];
};

// 搜索处理
const searchHandle = (key) => {
  if (!isString(key) || !key.length) {
    closeHandle();
    return;
  }
  loading.value = true;
  showPopover.value = true;
  searchRes.value = List.filter(
    (e) =>
      !e.disabled && (!key || e.title.toLowerCase().includes(key.toLowerCase()))
  );
  setTimeout(() => {
    loading.value = undefined;
  }, 500);
};

// 关闭处理
const listenerCloseHandle = (e) => {
  if (!showPopover.value) return;
  if (!e.target) return;
  if (!e.target.closest(".go-chart-search")) {
    closeHandle();
  }
};

// 选择处理
const selectChartHandle = async (item) => {
  if (item.disabled) return;
  try {
    // 动态注册图表组件
    componentInstall(item.chartKey, fetchChartComponent(item));
    componentInstall(item.conKey, fetchConfigComponent(item));
    // 创建新图表组件
    let newComponent = await createComponent(item);
    if (item.redirectComponent) {
      item.dataset && (newComponent.option.dataset = item.dataset);
      newComponent.chartConfig.title = item.title;
      newComponent.chartConfig.chartFrame = item.chartFrame;
    }
    store.commit("chartEditStore/ADD_COMPONENTLIST", newComponent); // 添加
    store.commit("chartEditStore/SET_SELECTCOMPONENT", newComponent); // 选中
    // 清空搜索
    closeHandle();
  } catch (error) {}
};

// 聚焦设置
const focusHandle = (value) => {
  isFocus.value = value;
};

// 修改图表展示方式
const changeChartModeType = (value) => {
  chartMode.value = value;
  store.commit("chartLayoutStore/SET_CHART_TYPE", value);
};

addEventListener(document, "click", (e) => {
  listenerCloseHandle(e);
});

onUnmounted(() => {
  removeEventListener(document, "click", listenerCloseHandle);
});
</script>

<style lang="scss" scoped>
$width: 85px;
$searchWidth: 146px;

.search-box {
  display: flex;
  align-items: center;
}

.chart-search {
  width: $width;
  margin-right: 2px;
  &.chart-search-focus {
    width: $searchWidth;
    &.chart-search {
      margin-right: 0;
    }
  }
}
</style>

<style lang="scss">
.chart-search-popover {
  padding-left: 5px;
  padding-right: 8px;

  .search-list-box {
    width: 163px;

    .list-item {
      z-index: 2;
      position: relative;
      cursor: pointer;
      padding: 2px;
      padding-left: 6px;
      margin-bottom: 5px;
      display: flex;
      align-items: center;
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-break: break-all;

      &-fs {
        font-size: 12px;
      }

      &-img {
        height: 20px;
        width: 30px;
        margin-right: 5px;
        border-radius: 5px;
        img {
          width: 100%;
          height: 100%;
        }
      }

      &:hover {
        &::before {
          content: "";
          position: absolute;
          width: 3px;
          height: 100%;
          left: 0;
          top: 0;
          border-radius: 2px;
          background-color: v-bind("themeColor");
        }
        &::after {
          z-index: -1;
          content: "";
          position: absolute;
          width: 100%;
          height: 100%;
          opacity: 0.1;
          background-color: v-bind("themeColor");
        }
      }

      .popover-modal {
        position: absolute;
        width: 100%;
        height: 100%;
        z-index: 1;
        opacity: 0;
      }
    }
  }
}
</style>
